<template>
    <el-card>
        <el-form :inline="true" class='form'>
            <el-form-item label="用户名:">
                <el-input v-model="user" placeholder="请输入搜索的用户名" class="w-60" />
            </el-form-item>

            <el-form-item class="float-right">
                <el-button type="primary" @click="search" :disabled="user ? false : true">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>



    </el-card>

    <el-card class="mt-3">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button type="danger" @click="removeUser" :disabled="removeid?false:true">批量删除</el-button>
        <el-table border class="mt-3" :data="allUser" @selection-change="handleSelectionChange">
            <el-table-column type="selection"></el-table-column>
            <el-table-column type="index" label="#" align="center" width="50"></el-table-column>
            <el-table-column property="id" align="center" label="ID"></el-table-column>
            <el-table-column property="username" align="center" label="用户名字"></el-table-column>
            <el-table-column property="name" align="center" label="用户名称"></el-table-column>
            <el-table-column property="roleName" align="center" label="用户角色"></el-table-column>
            <el-table-column property="createTime" align="center" label="创建时间"></el-table-column>
            <el-table-column property="updateTime" align="center" label="更新时间"></el-table-column>
            <el-table-column label="操作" align="center" width="350">
                <template #="{ row }">
                    <el-button type="primary" size="small" @click="setRole(row)" icon="UserFilled">分配角色</el-button>
                    <el-button type="primary" size="small" @click="Edit(row)" icon="Edit">编辑</el-button>

                    <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" icon="Delete"
                        icon-color="#F56C6C" :title="`确定要删除用户${row.username}吗?`" @confirm="remove(row)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>

                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>


        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
            :background="true" layout="  prev, pager, next, jumper,->,sizes,total," :total="total" class="mt-3"
            @size-change="handleSizeChange" @current-change="getAlluser" />
    </el-card>


    <!-- 新增与更新用户数据的数据的抽屉 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>{{ userParams.id ? '更新用户' : '新增用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userParams" :rules="rules" ref="ruleFormRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请填写用户名字" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请填写用户昵称" v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="pwd" v-if="!userParams.id">
                    <el-input placeholder="请填写用户密码" v-model="userParams.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 分配角色的抽屉 -->
    <el-drawer v-model="drawer1">
        <template #header>
            <h4>分配角色(职位)</h4>
        </template>
        <template #default>
            <el-form width-label="150">
                <el-form-item label="用户姓名">
                    <el-input disabled v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                    <!-- 显示职位的的复选框 -->
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(city,index) in allRole" :key="index" :label="city">{{
                            city.roleName
                        }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="">取消</el-button>
                <el-button type="primary" @click="confirmClick">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入接口
import { reqUserInfo, reqUserDelete, reqAddOrUpdateUser ,reqAllRole ,reqSetUserRole ,reqSelectUser} from '@/api/acl/user/index'

//搜索框中的值
const user = ref<any>('')

//分页器当前的页码
let pageNo = ref<any>(1)
//每一页展示的数据条数
let pageSize = ref<any>(5)
//总数据
let total = ref<any>()
//渲染的所有数据
let allUser = ref<any>()
//定义一个响应式数据抽屉的显示与隐藏
let drawer = ref<boolean>(false)
//定义一个响应式数据抽屉的显示与隐藏
let drawer1 = ref<boolean>(false)
//校验规则的实例
let ruleFormRef = ref<any>()
//收集用户信息的响应式数据
let userParams = reactive<any>({
    username: '',
    name: '',
    password: ''
})




//删除存放的id
let removeid = ref<any>()
//钩子函数 进去页面直接调用请求的函数 执行渲染
onMounted(() => {
    getAlluser()
})

//请求全部用户数据
const getAlluser = async (pager = 1) => {
    pageNo.value = pager
    let result: any = await reqUserInfo(pageNo.value,pageSize.value,user.value)
    if (result.code == 200) {
        allUser.value = result.data.records
        total.value = result.data.total
    }
}

//分页器下拉请求展示数据
const handleSizeChange = () => {
    getAlluser()
}

//添加用户按钮的回调
const addUser = () => {
    // userParams.value=''
    //在点击新增按钮后清空表达内容数据
    Object.assign(userParams, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
    drawer.value = true
    nextTick(() => {
        ruleFormRef.value.clearValidate('username')
        ruleFormRef.value.clearValidate('name')
        ruleFormRef.value.clearValidate('pwd')
    })


}
//更新数据
//row 即为用户的账号信息
const Edit = (row: any) => {
    drawer.value = true
    Object.assign(userParams, row)
    nextTick(() => {
        ruleFormRef.value.clearValidate('username')
        ruleFormRef.value.clearValidate('name')
    })

}
//新增或是更新的按钮回调
const save = async () => {
    //在点击按钮时 要保证表单所有规则通过才可以发送请求 
    ruleFormRef.value.validate()
    const result: any = await reqAddOrUpdateUser(userParams)
    if (result.code == 200) {
        drawer.value = false

        ElMessage({
            showClose: true,
            message: userParams.id ? '修改成功!' : '新增成功!',
            type: 'success',
        })
        window.location.reload();

    } else {
        drawer.value = false
        ElMessage({
            showClose: true,
            message: userParams.id ? '修改失败!' : '新增失败!',
            type: 'error',
        })
    }
    getAlluser()

}


//抽屉中取消按钮的回调
const cancel = () => {
    drawer.value = false
    drawer1.value = false

}

//校验用户名字的回调函数
const ValidatorUsername = (rule: any, value: any, callback: any) => {
    console.log(rule);
    
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error('字符长度需大于等于五位'))
    }
}
//校验用户昵称的回调函数
const ValidatorName = (rule: any, value: any, callback: any) => {
    console.log(rule);

    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error('字符长度需大于等于五位'))

    }
}
//校验用户昵称的回调函数
const ValidatorPassword = (rule: any, value: any, callback: any) => {
    console.log(rule);

    if (value.trim().length >= 6) {
        callback()
    } else {
        callback(new Error('字符长度需大于等于五位'))

    }
}
//表单验证规则
const rules = reactive<any>({
    username: [
        { required: true, message: '请输入正确的姓名', trigger: 'blur', validator: ValidatorUsername },
    ],
    name: [
        { required: true, message: '请输入规范的用户昵称', trigger: 'blur', validator: ValidatorName },
    ],
    pwd: [
        { required: true, message: '请输入正确的用户密码', trigger: 'blur', validator: ValidatorPassword },
    ],
})


//分配角色中的职位列表
//全选框收集数据:是否全选
const checkAll = ref<boolean>(false)
//设置不确定的状态,仅负责样式控制
const isIndeterminate = ref<boolean>(true)
const userRole = ref<any>([])
const allRole =ref<any>([])

// 分配角色按钮的回调
const setRole = async(row:any) => {
    Object.assign(userParams,row)
    let result:any=await reqAllRole(userParams.id)
    if(result.code==200){
        allRole.value=result.data.allRolesList  
        userRole.value=result.data.assignRoles
    }   
    drawer1.value = true
}
const handleCheckAllChange = (val: boolean) => {
    userRole.value = val ? allRole.value : []
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === allRole.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.length
}

//确定按钮的回调(分配职位)
const confirmClick=async()=>{
    //收集参数
    let data:any=  {
        userId:userParams.id,
        roleIdList:userRole.value.map(item=>item.id)
    }
    let result:any= await reqSetUserRole(data)
    if (result.code==200) {
        ElMessage({
            showClose: true,
            message: '分配职务成功!',
            type: 'success',
        })
    getAlluser()
    }
    drawer1.value = false
}
// 表格的行选中状态id
const handleSelectionChange = (val: any) => {
    removeid.value=val
}

//批量删除按钮的回调
const removeUser =async () => {
    let idList:any= removeid.value.map(item=>item.id)
    console.log(idList);
    
    let result:any=await reqSelectUser(idList)
    console.log(result);

    if (result.code == 200) {
        ElMessage({
            showClose: true,
            message: '删除成功!',
            type: 'success',
        })
    getAlluser()
    }else{
        ElMessage({
            showClose: true,
            message: '删除失败!',
            type: 'info',
        })
    }

    
}
//删除用户按钮的回调
const remove = async (row: any) => {
    let result: any = await reqUserDelete(row.id)
    if (result.code == 200) {
        ElMessage({
            showClose: true,
            message: '删除成功!',
            type: 'success',
        })
        getAlluser()
    }else{
        ElMessage({
            showClose: true,
            message: '删除失败!',
            type: 'info',
        })
    }
    
}

//搜索按钮的回调
const search=()=>{
    getAlluser()
   user.value=''
}
//重置按钮的回调
const reset=()=>{
    user.value=''
    getAlluser()
}
</script>

<style lang="scss" scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>